package com.xsqf.jt808.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class CrossDomainFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

//        log.debug("CrossDomainFilter - doFilter - start");

        HttpServletResponse res = (HttpServletResponse) response;

        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Authorization-Token,sessionToken,appVersion,accessToken,ip,ipcname,sourceType");

        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
//            log.debug("CrossDomainFilter - doFilter - receive options req, return ok");
            return;
        }

        chain.doFilter(request, response);

//        log.debug("CrossDomainFilter - doFilter - end");
    }

    @Override
    public void destroy() {
        log.debug("CrossDomainFilter - destroy");
    }

//    @Override
//    public void init(FilterConfig filterConfig) {
//    }
}
